#!/usr/bin/env python

# coding=utf-8
from abc import ABCMeta

from CommonLib import *
from com_232_driver import *
from SendWrap import *


class DriverThread(threading.Thread):

    def ReadHandler(self, params):
        # print('ReadHandler',params)
        s = SendWrap(host_ins_new_device_addr)
        s.SendData(params)

    def __init__(self):
        super(DriverThread, self).__init__()
        self.com = Com232Driver(self.ReadHandler)
        self.pre_data = None

    def SendData(self, data):
        self.pre_data = data
        if self.pre_data is not None:
            self.com.send(self.pre_data)
            self.pre_data = None

    def run(self):
        while True:
            time.sleep(1000)


t1 = DriverThread()


class IndexHandler(tornado.web.RequestHandler):
    __metaclass__ = ABCMeta

    def post(self):
        self.get()

    def get(self):
        greeting = self.get_argument('greeting', 'Hello')
        respon = {'from interface index': greeting}
        respon_json = tornado.escape.json_encode(respon)
        con.commit()

        self.write(respon_json)
        # self.write(greeting + ', friendly user!')


class SendToDeviceHandler(tornado.web.RequestHandler):
    __metaclass__ = ABCMeta

    def post(self):
        print(self.request.path)
        try:
            jsono = json.loads(self.request.body)
        except Exception as e:
            print('exception' + e.message)
            return
        t1.SendData(jsono)
        retO = dict()
        retO['code'] = 0
        retO['desc'] = ''
        self.finish(json.dumps(retO))


if __name__ == "__main__":
    logging.getLogger("requests").setLevel(logging.WARNING)
    logging.getLogger("tornado").setLevel(logging.DEBUG)
    import os
    fileHandler = logging.FileHandler(os.getcwd()+"/com-server.log")
    fileHandler.setLevel(logging.DEBUG)
    fileFormatter = logging.Formatter('[%(levelname)s %(asctime)s %(filename)s:%(lineno)d] %(message)s')
    fileHandler.setFormatter(fileFormatter)
    logging.root.addHandler(fileHandler)
    logging.root.setLevel(logging.DEBUG)
    t1.setDaemon(True)
    t1.start()
    tornado.options.parse_command_line()

    app = tornado.web.Application(
        handlers=[
            (r"/", IndexHandler),
            (r"/send_to_device", SendToDeviceHandler),

        ],
        autoreload=False,
        debug=False
    )
    http_server = tornado.httpserver.HTTPServer(app)
    # http_server.listen(options.port)
    http_server.listen(60001)
    tornado.ioloop.IOLoop.instance().start()
